package com.vlin.scene.actuator.defaut;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.vlin.entity.scene.Command;
import com.vlin.entity.scene.TimerEvent;
import com.vlin.scene.actuator.CommandHandler;
import com.vlin.scene.actuator.CommandHandlerManager;
import com.vlin.scene.actuator.ListCommandHandler;
import com.vlin.scene.actuator.TimerExecutor;

public class DefaultTimerExecutor implements TimerExecutor,CommandHandlerManager {

	private Timer timer = new Timer();
	
	private ListCommandHandler commandHandler = new DefaultListCommandHandler();
	
	@Override
	public void execute(TimerEvent timerEvent) {
		if(timerEvent != null) {
			timer.schedule(new DefaultTimerTask(timer, timerEvent, commandHandler), timerEvent.getDelay());
		}
		
	}
	
	public static class DefaultTimerTask extends TimerTask {

		private final Timer timer;
		
		private final TimerEvent timerEvent;
		
		private final CommandHandler commandHandler;
		
		
		public DefaultTimerTask(Timer timer, TimerEvent timerEvent, CommandHandler commandHandler) {
			
			this.timer = timer;
			this.timerEvent = timerEvent;
			this.commandHandler = commandHandler;
		}
		
		@Override
		public void run() {
			
			if(timer == null) {
				return;
			}
			
			if(timerEvent != null && timerEvent.getList() != null) {
				List<Command> list = timerEvent.getList();
				for(Command command : list) {
					if(commandHandler != null) {
						if(commandHandler.support(command)){
							commandHandler.handle(command);
						}
					}
				}
			}
			TimerEvent event = timerEvent.getEvent();
			if(event != null) {
				timer.schedule(new DefaultTimerTask(timer, timerEvent, commandHandler), event.getDelay());
			}else {
				timer.cancel();
			}
		}
	}


	@Override
	public void addCommandHandler(CommandHandler commandHandler) {
		
		this.commandHandler.addCommandHandler(commandHandler);
	}


	@Override
	public void setListCommandHandler(ListCommandHandler listCommandHandler) {
		if(listCommandHandler != null) {
			this.commandHandler = listCommandHandler;
		}
		
	}

	@Override
	public ListCommandHandler getListCommandHandler() {
		
		return this.commandHandler;
	}
	
	
}
